import {
  Bar,
  BarChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import React, { useMemo, useState } from "react";
import { usePrediction } from "@/api/prediction";
import { MONTHS } from "@/feature/PredictionTable/helper";
import { MonthSelector } from "@/components/Dashboard/MonthSelector";
import { OptionI } from "@/models/common";
import cls from "@/styles/feature/PredictionBarChart.module.scss";
import { SpecSelector } from "@/components/Dashboard/SpecSelector";
import { YearSelector } from "@/components/Dashboard/YearSelector";

export const PredictionBarChart = () => {
  const [month, setMonth] = useState<OptionI>();
  const [spec, setSpec] = useState<OptionI>();
  const [year, setYear] = useState<OptionI>();
  const params = useMemo(() => {
    return new URLSearchParams({
      month: String(month?.id || 2),
      year: String(year?.id || 2024),
    });
  }, [month]);
  const [dataPag, monthData, isLoading] = usePrediction(params);
  const data = useMemo(() => {
    if (!monthData || monthData.length === 0) return [];

    const m = monthData[0];
    const getName = (week: number): string => {
      return `${week} неделя ${m.year} (${MONTHS[m.month]})`;
    };

    return m.weeks
      .filter((w) => w.specialization.id === spec.id)
      .map((w) => {
        return {
          name: getName(w.week),
          pred: w.qtty_predicted,
          fact: w.qtty,
        };
      });
  }, [monthData, spec, year]);
  return (
    <div className={cls.root}>
      <div className={cls.selectors}>
        <div className={cls.selectors_left}>
          <SpecSelector setSpec={setSpec} />
        </div>
        <div className={cls.selectors_right}>
          <MonthSelector setMonth={setMonth} />
          <YearSelector setYear={setYear} />
        </div>
      </div>

      <ResponsiveContainer width="100%" height="80%">
        <BarChart data={data}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="name" />
          <YAxis />
          <Tooltip />
          <Bar name="План" dataKey="pred" stackId="a" fill="#6366F1" />
          <Bar name="Факт" dataKey="fact" stackId="b" fill="#174191" />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
};
